<template>
  <div>
    <el-card class="box-card">
      <div
        slot="header"
        class="clearfix"
      >
        <span>组织机构树</span>
        <el-button
          v-if="checkPermission(['AbpIdentity.OrganizationUnits.Create'])"
          style="float: right;"
          type="primary"
          icon="ivu-icon ivu-icon-md-add"
          @click="handleCreateRootOrganizationUnit(null)"
        >
          添加根机构
        </el-button>
      </div>
      <div>
        <el-tree
          ref="organizationUnitTree"
          node-key="id"
          :props="organizationProps"
          :data="organizationUnits"
          draggable
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          icon-class="el-icon-arrow-right"
          :allow-drag="handleAllowDrag"
          :allow-drop="handleAllowDrop"
          @node-drop="handleNodeDroped"
          @node-click="handleNodeClick"
          @node-contextmenu="onContextMenu"
        />
      </div>
    </el-card>

    <user-reference
      :organization-unit-id="editOrganizationUnitId"
      :show-dialog="showUserReferenceDialog"
      @closed="() => {
        showUserReferenceDialog = false
      }"
    />

    <role-reference
      :organization-unit-id="editOrganizationUnitId"
      :show-dialog="showRoleReferenceDialog"
      @closed="() => {
        showRoleReferenceDialog = false
      }"
    />

    <create-or-update-organization-unit
      :is-edit="isEditOrganizationUnit"
      :title="editOrganizationUnitTitle"
      :show-dialog="showOrganizationUnitDialog"
      :organization-unit-id="editOrganizationUnitId"
      :on-organization-unit-changed="onOrganizationUnitChanged"
      @closed="onOrganizationUnitDialogClosed"
    />
  </div>
</template>

<script>
import UserReference from './UserReference'
import RoleReference from './RoleReference'
import CreateOrUpdateOrganizationUnit from './CreateOrUpdateOrganizationUnit'
import { getList, move, deleteOrganizationUnit } from '@/api/organizationunit'
import checkPermission from '@/utils/permission' // 权限判断函数
import { Vue } from 'vue-property-decorator'

const $contextmenu = Vue.prototype.$contextmenu

export default {
  name: 'OrganizationUnitTree',
  components: {
    UserReference,
    RoleReference,
    CreateOrUpdateOrganizationUnit
  },
  props: { },
  data() {
    return {
      showUserReferenceDialog: false,
      showRoleReferenceDialog: false,
      showOrganizationUnitDialog: false,
      isEditOrganizationUnit: false,
      editOrganizationUnitId: '',
      editOrganizationUnitTitle: '',
      organizationUnits: [],
      currentEditNode: {},
      organizationProps: {
        label: 'displayName',
        children: 'children'
      },
      textMap: {
        update: '编辑',
        create: '添加',
        preview: '查看'
      },
      rules: {
        executionTime: [{ required: true, message: '必须填写', trigger: 'blur' }],
        executionDuration: [{ required: true, message: '必须填写', trigger: 'blur' }]
      },
      downloadLoading: false,
      loading: false,
      tempRoute: {},
      activeNames: ['1']
    }
  },
  created() {
    this.handleGetOrganizationUnits()
  },
  methods: {
    checkPermission,
    setTagsViewTitle() {
      let title = this.textMap.create
      if (this.temp.id) {
        title = this.textMap.update
      }
      if (this.isPreview) {
        title = this.textMap.preview
      }

      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.temp.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    onOrganizationUnitChanged(ou) {
      console.log(ou)
    },
    handleGetOrganizationUnits() {
      getList().then(res => {
        const rootOrganizationUnits = res.data.items.filter(item => !item.parentId)
        rootOrganizationUnits.forEach(item => {
          const organizationUnit = {
            id: item.id,
            parentId: item.parentId,
            code: item.code,
            displayName: item.displayName,
            children: []
          }
          const subOrganizationUnits = res.data.items.filter(p => p.code.startsWith(item.code))
          this.generateOrganizationUnit(organizationUnit, subOrganizationUnits)
          this.organizationUnits.push(organizationUnit)
        })
      })
    },
    generateOrganizationUnit(organizationUnit, organizationUnits) {
      const subOrganizationUnit = organizationUnits.filter(ou => ou.parentId !== organizationUnit.id)
      organizationUnits = organizationUnits.filter(ou => ou.parentId === organizationUnit.id)
      organizationUnits.forEach(ou => {
        const children = {
          id: ou.id,
          parentId: ou.parentId,
          code: ou.code,
          displayName: ou.displayName,
          children: []
        }
        const itemSubOrganizationUnit = subOrganizationUnit.filter(sou => sou.parentId === ou.id)
        if (itemSubOrganizationUnit.length > 0) {
          this.generateOrganizationUnit(children, itemSubOrganizationUnit)
        }
        organizationUnit.children.push(children)
      })
    },
    onContextMenu(event, ou) {
      const organizationUnitTree = this.$refs.organizationUnitTree
      $contextmenu({
        items: [
          {
            label: '编辑',
            icon: 'el-icon-edit',
            disabled: !checkPermission(['AbpIdentity.OrganizationUnits.Update']),
            onClick: () => {
              this.editOrganizationUnitTitle = '编辑'
              this.isEditOrganizationUnit = true
              this.editOrganizationUnitId = ou.id
              this.showOrganizationUnitDialog = true
              this.onOrganizationUnitChanged = (res) => {
                ou.displayName = res.displayName
              }
            }
          },
          {
            label: '添加子机构',
            icon: 'ivu-icon ivu-icon-md-add',
            disabled: !checkPermission(['AbpIdentity.OrganizationUnits.Create']),
            onClick: () => {
              this.handleCreateRootOrganizationUnit(ou)
            }
          },
          {
            label: '添加成员',
            disabled: !checkPermission(['AbpIdentity.OrganizationUnits.ManageUsers']),
            onClick: () => {
              this.editOrganizationUnitId = ou.id
              this.showUserReferenceDialog = true
            }
          },
          {
            label: '添加角色',
            disabled: !checkPermission(['AbpIdentity.OrganizationUnits.ManageRoles']),
            onClick: () => {
              this.editOrganizationUnitId = ou.id
              this.showRoleReferenceDialog = true
            }
          },
          {
            label: '删除',
            icon: 'el-icon-delete',
            disabled: !checkPermission(['AbpIdentity.OrganizationUnits.Delete']),
            onClick: () => {
              this.$confirm(`是否删除组织机构[${ou.displayName}]`,
                '确认', {
                  callback: (action) => {
                    if (action === 'confirm') {
                      deleteOrganizationUnit(ou.id).then(() => {
                        organizationUnitTree.remove(ou)
                        // 所有根节点已经被删除
                        if (organizationUnitTree.data.length === 0) {
                          this.$emit('onOrganizationUnitChecked', '')
                        }
                      })
                    }
                  }
                })
            }
          }
        ],
        event,
        customClass: 'context-menu',
        zIndex: 2,
        minWidth: 150
      })
    },
    onOrganizationUnitDialogClosed() {
      this.showOrganizationUnitDialog = false
    },
    handleCreateRootOrganizationUnit(ou) {
      const organizationUnitTree = this.$refs.organizationUnitTree
      this.editOrganizationUnitTitle = '添加子机构'
      this.isEditOrganizationUnit = false
      if (ou) {
        this.editOrganizationUnitId = ou.id
        this.onOrganizationUnitChanged = (res) => {
          organizationUnitTree.append(res, ou)
        }
      } else {
        this.editOrganizationUnitId = ''
        this.onOrganizationUnitChanged = (res) => {
          if (this.organizationUnits.length > 0) {
            const lastNode = organizationUnitTree.getNode(this.organizationUnits[this.organizationUnits.length - 1].id)
            organizationUnitTree.insertAfter(res, lastNode)
          } else {
            this.handleGetOrganizationUnits()
          }
        }
      }
      this.showOrganizationUnitDialog = true
    },
    handleAllowDrag(draggingNode) {
      return draggingNode.data.parentId !== undefined && draggingNode.data.parentId !== null
    },
    handleAllowDrop(draggingNode, dropNode) {
      return dropNode.code !== 'root'
    },
    handleNodeDroped(draggingNode, dropNode) {
      move(draggingNode.data.id, dropNode.data.id).then(() => {
        this.handleGetOrganizationUnits()
      })
    },
    handleNodeClick(data) {
      if (data.id !== undefined) {
        this.$emit('onOrganizationUnitChecked', data.id)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
